<template class="firstpage">
  <div>
    <div class="boxMargin">
      <el-form ref="form" :model="form" :rules="rules" label-width="150px" class="demo-ruleForm">
        <el-form-item label="主图视频名称：" prop="videoName">
          <el-input v-model="form.videoName" class="w30" :disabled="customData.nameType == '1'" />
        </el-form-item>
        <el-form-item label="主图视频简介：">
          <el-input v-model="form.videoDesc" class="w30" :disabled="customData.nameType == '1'" />
        </el-form-item>
        <el-form-item label="主图视频：" prop="videoUrl">
          <div class="listImg">
            <div v-if="form.videoUrl != ''" class="drawing_div">
              <video :src="form.videoUrl" class="avatar" autoplay controls="controls" style="max-width:100%;max-height:100%">您的浏览器不支持视频播放</video>
            </div>
          </div>
          <div class="listImg">
            <div class="drawing_div" @click="spzst('1')">
              <i class="el-icon-plus" />
            </div>
          </div>
        </el-form-item>
        <el-form-item>
          <el-button type="danger" @click="empty('1')">清空主图视频</el-button>
        </el-form-item>
        <el-form-item label="商详视频名称：" prop="videoNameFu">
          <el-input v-model="form.videoNameFu" class="w30" :disabled="customData.shangType == '1'" />
        </el-form-item>
        <el-form-item label="商详视频简介：">
          <el-input v-model="form.videoDescFu" class="w30" :disabled="customData.shangType == '1'" />
        </el-form-item>
        <el-form-item label="商详视频：" prop="videoUrlFu">
          <div class="listImg">
            <div v-if="form.videoUrlFu != ''" class="drawing_div">
              <video :src="form.videoUrlFu" class="avatar" autoplay controls="controls" style="max-width:100%;max-height:100%">您的浏览器不支持视频播放</video>
            </div>
          </div>
          <div class="drawing_div" @click="spzst('2')">
            <i class="el-icon-plus" />
          </div>
        </el-form-item>
        <el-form-item>
          <el-button type="danger" @click="empty('2')">清空商详视频</el-button>
        </el-form-item>
        <el-form-item>
          <el-row>
            <el-col :span="24" style="text-align: center;margin-top:20px;">
              <el-button type="success" @click="infoUpdate('form')">保存</el-button>
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>
    </div>
    <el-dialog title="添加" :visible.sync="customData.modality" width="80%" @close="closeDialog">
      <el-tabs v-model="customData.activeName" type="border-card" style="min-height:320px;" @tab-click="handleClick">
        <el-tab-pane label="视频管理" name="first">
          <el-row>
            <el-col :span="8" class="inputName">
              <el-input v-model="searchData.fvideoName" placeholder="请输入视频名称进行检索" />
            </el-col>
            <el-col :span="8">
              <el-button type="primary" @click="onSearch">搜索</el-button>
            </el-col>
          </el-row>
          <el-radio-group v-model="customData.radioId" style="margin-top:20px;">
            <div v-for="item in tableData" :key="item.id" style="width:300px;height:200px;display:inline-block;margin-right:20px;">
              <video v-if="item.uploadId == ''" :src="item.samsVideoUrl" class="avatar" autoplay controls="controls" style="max-width:100%;max-height:100%">您的浏览器不支持视频播放</video>
              <video v-if="item.uploadId != ''" :src="item.extDomain + item.videoPreview +item.uploadId" class="avatar" autoplay controls="controls" style="max-width:100%;max-height:100%">您的浏览器不支持视频播放</video>
              <el-radio :label="item.id" class="radio-item">{{ item.videoName }}</el-radio>
            </div>
          </el-radio-group>
          <div class="center">
            <el-pagination
              :current-page="pageData.pageNo"
              :page-sizes="pageData.pageSizes"
              :page-size="pageData.pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="pageData.total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
          <el-row>
            <el-col :span="12" style="text-align: right;margin-top:20px;">
              <el-button type="primary" @click="videoLibrary">确认</el-button>
            </el-col>
          </el-row>
        </el-tab-pane>
        <el-tab-pane label="本地上传" name="second">
          <div style="display:flex;">
            <div v-if="form.videoUrl != '' && customData.statusType == '1'" class="drawing_div" style="width:136px;height:136px;margin-right:20px;">
              <video :src="form.videoUrl" class="avatar" autoplay controls="controls" style="max-width:100%;max-height:100%">您的浏览器不支持视频播放</video>
            </div>
            <div v-if="form.videoUrlFu != '' && customData.statusType == '2'" class="drawing_div" style="width:136px;height:136px;margin-right:20px;">
              <video :src="form.videoUrlFu" class="avatar" autoplay controls="controls" style="max-width:100%;max-height:100%">您的浏览器不支持视频播放</video>
            </div>
            <el-upload ref="upload" action :show-file-list="false" :auto-upload="false" :on-change="beforeAvatarUploadType" accept=".mp4">
              <div style="border-radius: 6px;background-color: #fbfdff;width:136px;height:136px;box-sizing:border-box;border:1px dashed #c0ccda;display:flex;justify-content: center;align-items: center;">
                <i class="el-icon-plus" />
              </div>
            </el-upload>
          </div>
          <div>
            <p>上传说明：</p>
            <p>1：视频格式支持.mp4</p>
            <p>2：最大允许上传200MB视频</p>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>
  </div>
</template>
<script>
import _validate from '../../../../../framework/commonJs/wptx_validate'
import _api from '@/framework/API/generalItem'
import _materialApi from '@/framework/API/material'
import { global } from '../../../../../filter/global-api'
import SparkMD5 from 'spark-md5'
const _FUNCTION_NAME = ''
export default {
  filters: {},
  data() {
    const videoNameDator = (rule, value, callback) => {
      if (this.form.videoUrl != undefined && this.form.videoUrl != null && this.form.videoUrl != '') {
        if (value == undefined || value == null || value == '') {
          callback(new Error('请输入主图视频名称'))
        }
      }
      callback()
    }
    const videoNameFuDator = (rule, value, callback) => {
      if (this.form.videoUrlFu != undefined && this.form.videoUrlFu != null && this.form.videoUrlFu != '') {
        if (value == undefined || value == null || value == '') {
          callback(new Error('请输入商详视频名称'))
        } else {
        }
      }
      callback()
    }
    const videoUrlDator = (rule, value, callback) => {
      if (this.form.videoName != undefined && this.form.videoName != null && this.form.videoName != '') {
        if (value == undefined || value == null || value == '') {
          callback(new Error('请上传主图视频'))
        }
      }
      callback()
    }
    const videoUrlFuDator = (rule, value, callback) => {
      if (this.form.videoNameFu != undefined && this.form.videoNameFu != null && this.form.videoNameFu != '') {
        if (value == undefined || value == null || value == '') {
          callback(new Error('请上传商详视频'))
        }
      }
      callback()
    }
    return {
      tableData: [],
      searchData: {
        fvideoName: '' // 视频名称
      },
      searchDataBuffer: {
        fvideoName: '' // 视频名称
      },
      pageData: {
        pageNo: 1,
        pageSize: 10,
        total: 1,
        pageSizes: [10, 20, 50, 100]
      },
      dialogData: {},
      historyData: {},
      infoData: {},
      customData: {
        activeName: 'first',
        modality: false,
        videoList: [],
        statusType: '',
        masterItemId: '',
        nameType: '2',
        shangType: '2',
        videoDetail: {}, // 主图
        videoDetailFu: {}, // 商详
        radioId: ''
      },
      form: {
        videoName: '',
        videoDesc: '',
        videoUrl: '',
        videoSize: '',
        samsVideoUrl: '',
        videoId: '',
        // 商详
        videoNameFu: '',
        videoDescFu: '',
        videoSizeFu: '',
        videoUrlFu: '',
        samsVideoUrlFu: '',
        videoIdFu: ''
      },
      rules: {
        videoName: [
          { validator: videoNameDator, trigger: 'blur' }
        ],
        videoNameFu: [
          { validator: videoNameFuDator, trigger: 'blur' }
        ],
        videoUrl: [
          { validator: videoUrlDator, trigger: 'blur' }
        ],
        videoUrlFu: [
          { validator: videoUrlFuDator, trigger: 'blur' }
        ]
      }
    }
  },
  computed: {},
  watch: {
  },
  created() { },
  mounted() {
    this._FUNCTION_NAME = this.$route.name
    this.onInit()
  },
  beforeDestroy() { },
  methods: {
    onInit() {
      const self = this
      self.customData.masterItemId = sessionStorage.getItem('itemId')
      const data = {
        masterItemId: sessionStorage.getItem('itemId')
      }
      _api.videoDetail(self, data, self.callBack_videoDetail)
      const params = {
        pageNo: self.pageData.pageNo,
        pageSize: self.pageData.pageSize
      }
      _materialApi.videoPage(self, params, self.callBack_videoPage)
    },
    onSearch(data) {
      const self = this
      self.pageData.pageNo = 1
      const params = {
        pageNo: self.pageData.pageNo,
        pageSize: self.pageData.pageSize
      }
      const list = {
        fvideoName: self.searchData.fvideoName
      }
      _materialApi.videoPage(self, params, self.callBack_videoPage, list)
    },
    onChangePage(data) {
      const self = this
      const params = {
        pageNo: self.pageData.pageNo,
        pageSize: self.pageData.pageSize
      }
      const list = {
        fvideoName: self.searchData.fvideoName
      }
      _materialApi.videoPage(self, params, self.callBack_videoPage, list)
    },
    onReset(data) {
      const self = this
    },
    onAdd(data) { },
    onDelete(data) {
      const self = this
    },
    onInfo(data) {
      const self = this
    },
    onUpdate(formName) {
      const self = this
    },
    onBathDelete() {
      const self = this
    },
    onBathUpdate() { },
    onDisable(data) {
      const self = this
    },
    onEnable(data) {
      const self = this
    },
    onUpload(data) { },
    onBathUpload() { },
    onExport(data) { },
    onDownload(data) { },
    onHistory(data) { },
    callBack_videoDetail(data) {
      const self = this
      if (_validate.checkEmpty(data)) {
        _validate.openTip(self, '返回数据为空', 'warning')
      } else {
        if (data.data.videoList.length != 0) {
          data.data.videoList.forEach(item => {
            if (item.videoArea == 2) {
              self.customData.videoDetail = item
              self.form.videoName = item.videoName
              self.form.videoDesc = item.videoDesc
              if (_validate.checkEmpty(item.uploadId)) {
                self.form.videoUrl = item.samsVideoUrl
              } else {
                self.form.videoUrl = item.extDomain + item.videoPreview + item.uploadId
              }
              self.form.videoId = item.id
            }
            if (item.videoArea == 1) {
              self.customData.videoDetailFu = item
              self.form.videoNameFu = item.videoName
              self.form.videoDescFu = item.videoDesc
              if (_validate.checkEmpty(item.uploadId)) {
                self.form.videoUrlFu = item.samsVideoUrl
              } else {
                self.form.videoUrlFu = item.extDomain + item.videoPreview + item.uploadId
              }
              self.form.videoIdFu = item.id
            }
          })
        }
        if (!_validate.checkEmpty(self.form.videoUrl)) {
          self.customData.nameType = '1'
        }
        if (!_validate.checkEmpty(self.form.videoUrlFu)) {
          self.customData.shangType = '1'
        }
      }
    },
    // 视频库 的page回调
    callBack_videoPage(data) {
      const self = this
      if (_validate.checkEmpty(data)) {
        _validate.openTip(self, '返回数据为空', 'warning')
      } else {
        self.tableData = data.result
        self.pageData.total = data.totalCount
      }
    },
    // 更新视频
    callBack_videoUpdate(data) {
      const self = this
      if (_validate.checkEmpty(data)) {
        _validate.openTip(self, '返回数据为空', 'warning')
      } else {
        _validate.openTip(self, '更新成功', 'warning')
        self.onInit()
      }
    },
    spzst(value) {
      const self = this
      self.customData.statusType = value // 1是主图  2是商详
      self.customData.modality = true
      if (self.$refs.upload != undefined) { // 清空上传file里面的数据
        self.$refs.upload.clearFiles()
      }
    },
    // 关闭模态框
    closeDialog() {
      const self = this
      self.customData.modality = false
    },
    beforeAvatarUploadType(file, fileList) {
      const self = this
      const AllUpExt = '.mp4|'
      const extName = file.name.substring(file.name.lastIndexOf('.')).toLowerCase()
      const isLt10M = file.size / 1024 / 1024 < 200
      if (!isLt10M) {
        _validate.openTip(self, '文件大小不能超过200MB', 'warning')
        return false
      }
      if (AllUpExt.indexOf(extName + '|') == '-1') {
        _validate.openTip(self, '上传文件格式错误', 'warning')
        return false
      }
      if (self.customData.statusType == 1) {
        self.form.videoSize = (file.size / 1024 / 1024).toFixed(2)
      }
      if (self.customData.statusType == 2) {
        self.form.videoSizeFu = (file.size / 1024 / 1024).toFixed(2)
      }
      self.queryTenXunCosMsg(file)
    },
    queryTenXunCosMsg(file) {
      const self = this
      self.computeMD5(file)
    },
    // 计算MD5
    computeMD5(file) {
      const self = this
      const blobSlice = File.prototype.slice || File.prototype.mozSlice || File.prototype.webkitSlice
      const fileReader = new FileReader()
      const chunkSize = 2097152
      const chunks = Math.ceil(file.size / chunkSize)
      let currentChunk = 0
      let md5
      const spark = new SparkMD5.ArrayBuffer()
      fileReader.onload = function(e) {
        spark.append(e.target.result)
        currentChunk++
        if (currentChunk < chunks) {
          loadNext()
        } else {
          const sparkEnd = spark.end()
          const dataFile = file.raw
          const params = {
            uploadFile: dataFile,
            fileMd5: sparkEnd
          }
        }
      }
      fileReader.onerror = function() {
      }
      function loadNext() {
        const start = currentChunk * chunkSize
        const end = ((start + chunkSize) >= file.size) ? file.size : start + chunkSize
        fileReader.readAsArrayBuffer(blobSlice.call(file.raw, start, end))
      }
      loadNext()
    },
    // 上传的弹出层选择完视频
    itemUpload(file) {
      const self = this
      const fd = new FormData()
      fd.append('multiFile', file.raw)
      const url = process.env.VUE_APP_VIDEO_UPLOAD
      global.postupload(url, null, fd, function(response) {
        const res = JSON.parse(response)
        if (res.code != 200) {
          let msg = ''
          if (res.message) {
            msg = res.message
          } else {
            msg = res.msg
          }
          _validate.openTip(self, msg, 'error')
        } else {
          _validate.openTip(self, '视频上传成功', 'success')
          if (res.result) {
            // 1是主图  2是商详
            if (self.customData.statusType == 1) {
              self.form.videoUrl = res.result.videoUrl
              self.customData.videoDetail.uploadId = res.result.uploadId
              self.customData.nameType = '2'
              self.customData.videoDetail.domainName = res.result.domainName
              self.customData.videoDetail.videoDescId = ''
              self.customData.videoDetail.videoPlayTime = res.result.videoDuration
              self.customData.videoDetail.videoSize = res.result.videoSize
              self.customData.videoDetail.fileMd5 = res.result.videoMd5
            } else if (self.customData.statusType == 2) {
              self.form.videoUrlFu = res.result.videoUrl
              self.customData.videoDetailFu.uploadId = res.result.uploadId
              self.customData.shangType = '2'
              self.customData.videoDetailFu.domainName = res.result.domainName
              self.customData.videoDetailFu.videoDescId = ''
              self.customData.videoDetailFu.videoPlayTime = res.result.videoDuration
              self.customData.videoDetailFu.videoSize = res.result.videoSize
              self.customData.videoDetailFu.fileMd5 = res.result.videoMd5
            }
          }
        }
      },
      function(error) {
        self.$message.error('上传的视频错误，请重新上传！')
      }
      )
    },
    handleClick(tab) {
      const self = this
    },
    infoUpdate(formName) {
      const self = this
      const params = {
        list: [],
        masterItemId: self.customData.masterItemId
      }
      if (self.form.videoName != undefined && self.form.videoName != null && self.form.videoName != '') {
        params.list.push({
          videoArea: 2,
          domainName: self.customData.videoDetail.domainName,
          id: self.form.videoId,
          thumImgUrl: self.customData.videoDetail.thumImgUrl,
          thumUploadId: self.customData.videoDetail.thumUploadId,
          uploadId: self.customData.videoDetail.uploadId,
          videoDesc: self.form.videoDesc,
          videoName: self.form.videoName,
          videoType: 2,
          // videoUrl:self.form.videoUrl,
          samsVideoUrl: self.form.samsVideoUrl,
          videoPlayTime: self.customData.videoDetail.videoPlayTime,
          videoSize: self.form.videoSize,
          fileMd5: self.form.videoSizeFu
        })
      }
      if (self.form.videoNameFu != undefined && self.form.videoNameFu != null && self.form.videoNameFu != '') {
        params.list.push({
          videoArea: 1,
          domainName: self.customData.videoDetailFu.domainName,
          id: self.form.videoIdFu,
          thumImgUrl: self.customData.videoDetailFu.thumImgUrl,
          thumUploadId: self.customData.videoDetailFu.thumUploadId,
          uploadId: self.customData.videoDetailFu.uploadId,
          videoDesc: self.form.videoDescFu,
          videoName: self.form.videoNameFu,
          videoType: 2,
          // videoUrl:self.form.videoUrlFu,
          samsVideoUrl: self.form.samsVideoUrlFu,
          videoPlayTime: self.customData.videoDetailFu.videoPlayTime,
          videoSize: self.form.videoSizeFu,
          fileMd5: self.form.videoSizeFu
        })
      }
      self.$refs[formName].validate((valid) => {
        if (valid) {
          _api.videoUpdate(self, params, self.callBack_videoUpdate)
        } else {
          return false
        }
      })
    },
    videoLibrary() {
      const self = this
      if (self.tableData.length != 0) {
        self.tableData.forEach(item => {
          if (item.id == self.customData.radioId) {
            // 1是主图  2是商详
            if (self.customData.statusType == 1) {
              self.form.videoId = item.id
              self.customData.videoDetail.videoSize = item.videoSize
              self.form.videoName = item.videoName
              self.form.videoDesc = item.videoDesc
              if (_validate.checkEmpty(item.uploadId)) {
                self.form.videoUrl = item.samsVideoUrl
              } else {
                self.form.videoUrl = item.extDomain + item.videoPreview + item.uploadId
              }
              self.customData.nameType = '1'
              self.customData.videoDetail.videoDescId = item.id
            } else if (self.customData.statusType == 2) {
              self.form.videoIdFu = item.id
              self.customData.videoDetailFu.videoSize = item.videoSize
              self.form.videoNameFu = item.videoName
              self.form.videoDescFu = item.videoDesc
              if (_validate.checkEmpty(item.uploadId)) {
                self.form.videoUrlFu = item.samsVideoUrl
              } else {
                self.form.videoUrlFu = item.extDomain + item.videoPreview + item.uploadId
              }
              self.customData.shangType = '1'
              self.customData.videoDetailFu.videoDescId = item.id
            }
          }
        })
      }
      self.customData.modality = false
    },
    empty(value) {
      const self = this
      if (value == '1') {
        self.form.videoName = ''
        self.form.videoDesc = ''
        self.form.videoUrl = ''
        self.customData.nameType = '2'
      } else if (value == '2') {
        self.form.videoNameFu = ''
        self.form.videoDescFu = ''
        self.form.videoUrlFu = ''
        self.customData.shangType = '2'
      }
    },
    // 分页
    handleSizeChange(val) {
      const self = this
      self.pageData.pageNo = 1
      self.pageData.pageSize = val
      self.onChangePage()
    },
    handleCurrentChange(val) {
      const self = this
      self.pageData.pageNo = val
      self.onChangePage()
    }
  }
}
</script>

<style scoped>
.drawing_div{
    border-radius: 6px;
    background-color: #fbfdff;
    width: 300px;
    height: 150px;
    box-sizing:border-box;
    border:1px dashed #c0ccda;
    display:flex;
    justify-content: center;
    align-items: center;
}
.w30{
    width: 30%;
}
.listImg{
    float: left;
    margin-right: 20px;
}
.radio-item{
    margin-top:10px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    width: 100%;
    margin-bottom: 20px;
}
</style>
